package org.tlipoca.smcommentimage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.genntii.smcommon.constant.ExceptionConstant;
import org.genntii.smcommon.exception.CommentImageNotFoundException;
import org.genntii.smdomain.dto.CommentImageDTO;
import org.genntii.smdomain.entity.CommentImage;
import org.genntii.smdomain.vo.CommentImageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tlipoca.smcommentimage.mapper.CommentImageMapper;
import org.tlipoca.smcommentimage.service.CommentImageService;

import java.util.ArrayList;
import java.util.HashMap;

@Slf4j
@Service
public class CommentImageServiceImpl extends ServiceImpl<CommentImageMapper, CommentImage> implements CommentImageService {

    @Autowired
    private CommentImageMapper commentImageMapper;

    @Override
    public void deleteCommentImageByCommentIdService(Long commentId) {
        // 根据评论ID判断是否存在图片
        if(!commentImageMapper.exists(new QueryWrapper<CommentImage>().eq("comment_id", commentId))) {
            log.info("评论ID: {} 不存在图片", commentId);
            throw new CommentImageNotFoundException(ExceptionConstant.COMMENT_IMAGE_NOT_FOUND_EXCEPTION);
        }

        // 删除数据库
        commentImageMapper.deleteByCommentId(commentId);
    }

    @Override
    public void addCommentImageService(ArrayList<CommentImageDTO> commentImageDTOList) {
        commentImageMapper.insertBatch(commentImageDTOList);
    }

    @Override
    public HashMap<Long, ArrayList<CommentImage>> getCommentImageGroupByCommentIdListService(ArrayList<Long> commentIds) {

        ArrayList<CommentImage> commentImageList = commentImageMapper.selectCommentImageListByCommentIdList(commentIds);

        HashMap<Long, ArrayList<CommentImage>> map = new HashMap<>();
        for (CommentImage commentImage : commentImageList) {

            if(!map.containsKey(commentImage.getCommentId())) {
                map.put(commentImage.getCommentId(), new ArrayList<CommentImage>());
            }

            map.get(commentImage.getCommentId()).add(commentImage);
        }

        return map;
    }
}
